<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id='btn1'>点击发送</button>
    <button id='btn2'>点击发送</button>
    <script>
        // function fn1() {
        //     console.log('客户端函数被调用了')
        // }
    </script>
    <!-- <script src="http://localhost:3001/test"></script> -->
    <script>
        var btn1 = document.getElementById('btn1');
        var btn2 = document.getElementById('btn2');
        btn1.onclick = function() {

            JSONP({
                url: "http://localhost:3001/test",
                success: function(data) {
                    console.log('客户端函数被调用了1')
                    console.log(data)

                }
            })
        }
        btn2.onclick = function() {

            JSONP({
                url: "http://localhost:3001/test",
                data: {
                    name: 'zhangsan',
                    age: 20
                },
                success: function(data) {
                    console.log('客户端函数被调用了2')
                    console.log(data)
                }
            })
        }

        function JSONP(options) {
            var script = document.createElement('script');
            var FN = 'myJsonp' + Math.random().toString().replace('.', '')
            var params = '';
            for (var attr in options.data) {
                params += '&' + attr + '=' + options.data[attr];
            }
            script.src = options.url + '?callback=' + FN + params;
            window[FN] = options.success;
            document.body.appendChild(script)
            script.onload = function() {
                document.body.removeChild(script)
            }

        }
    </script>
</body>

</html>